<template>
  <div class="wechat-mnp-config">
    <div class="card-wrap mb10 animate-on-enter">
      <a-space wrap>
        <a-button :icon="h(ReloadOutlined)" @click="onRefresh" :loading="loading">
          刷新
        </a-button>
      </a-space>
    </div>

    <div class="card-wrap mb10 animate-on-enter animate-delay-1">
      <a-alert :message="formState.description" type="info" show-icon />
    </div>

    <div class="card-wrap animate-on-enter animate-delay-2">
      <a-spin :spinning="loading">
        <a-form ref="formRef" :model="formState" :label-col="{ span: 4 }" :wrapper-col="{ span: 16 }" :rules="rules"
          @finish="onSubmit" @finishFailed="onFinishFailed">
          <a-form-item label="AppID" :name="['config_value', 'app_id']">
            <a-input v-model:value="formState.config_value.app_id" placeholder="请输入微信小程序AppID" />
          </a-form-item>

          <a-form-item label="AppSecret" :name="['config_value', 'secret']">
            <a-input-password v-model:value="formState.config_value.secret" placeholder="请输入微信小程序AppSecret" />
          </a-form-item>

          <a-form-item label="Token" :name="['config_value', 'token']">
            <a-input v-model:value="formState.config_value.token" placeholder="请输入消息推送Token" />
          </a-form-item>

          <a-form-item label="EncodingAESKey" :name="['config_value', 'aes_key']">
            <a-input v-model:value="formState.config_value.aes_key" placeholder="请输入消息加解密密钥" />
          </a-form-item>

          <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
            <a-button type="primary" :icon="h(SaveOutlined)" html-type="submit" :loading="saveLoading">
              保存配置
            </a-button>
          </a-form-item>
        </a-form>
      </a-spin>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, h } from 'vue'
import { message } from 'ant-design-vue'
import { SaveOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import { getPlatformConfig, saveConfig } from '@/api/config'

// 响应式数据
const formRef = ref()
const loading = ref(false)
const saveLoading = ref(false)

// 表单数据
const formState = reactive({
  id: '',
  config_name: '微信小程序配置',
  config_key: 'wechat_mnp_config',
  config_value: {
    app_id: '',
    secret: '',
    token: '',
    aes_key: ''
  },
  description: '微信小程序基础配置信息'
})

// 表单验证规则
const rules = {
  config_value: {
    app_id: [
      { required: true, message: '请输入微信小程序AppID', trigger: 'change' },
    ],
    secret: [
      { required: true, message: '请输入微信小程序AppSecret', trigger: 'change' }
    ],
    token: [
      { required: true, message: '请输入消息推送Token', trigger: 'change' }
    ],
    aes_key: [
      { required: true, message: '请输入消息加解密密钥', trigger: 'change' }
    ]
  }
}

// 方法
const loadConfig = async () => {
  loading.value = true
  try {
    const response = await getPlatformConfig({
      config_key: 'wechat_mnp'
    })

    if (response.code === 200 && response.result) {
      // 如果有配置数据，则填充表单
      const config = response.result

      // 处理config_value，确保它是一个对象
      let configValue = config.config_value || {}
      if (typeof configValue === 'string') {
        try {
          configValue = JSON.parse(configValue)
        } catch (e) {
          console.error('解析config_value失败:', e)
          configValue = {}
        }
      }

      Object.assign(formState, {
        id: config.id || '',
        config_name: config.config_name || '微信小程序配置',
        config_key: config.config_key || 'wechat_mnp_config',
        config_value: {
          app_id: configValue.app_id || '',
          secret: configValue.secret || '',
          token: configValue.token || '',
          aes_key: configValue.aes_key || ''
        },
        description: config.description || '微信小程序基础配置信息'
      })
    }
  } catch (error) {
    console.error('加载配置失败:', error)
    message.error('加载配置失败')
  } finally {
    loading.value = false
  }
}

const onSubmit = async (values) => {
  saveLoading.value = true
  try {
    // 准备提交数据，将config_value转换为JSON字符串
    const submitData = {
      config_name: formState.config_name,
      config_key: formState.config_key,
      config_value: JSON.stringify(values.config_value),
      description: formState.description || ''
    }

    // 移除id字段，后端根据config_key判断新增还是更新
    delete submitData.id

    const response = await saveConfig(submitData)
    if (response.code === 200) {
      message.success('保存成功')
      // 重新加载配置
      await loadConfig()
    } else {
      message.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    message.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

const onFinishFailed = (errorInfo) => {
  console.log('表单验证失败:', errorInfo)
  message.error('请检查表单填写是否正确')
}

const onRefresh = () => {
  loadConfig()
}

// 生命周期
onMounted(() => {
  loadConfig()
})
</script>

<style scoped>
.wechat-mnp-config {
  .card-wrap {
    background: #fff;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    h3 {
      margin-bottom: 16px;
      color: #333;
      font-weight: 600;
    }
  }

  .mb10 {
    margin-bottom: 16px;
  }

  .mt10 {
    margin-top: 16px;
  }

  .animate-on-enter {
    animation: fadeInUp 0.6s ease-out;
  }

  .animate-delay-1 {
    animation-delay: 0.1s;
  }

  .animate-delay-2 {
    animation-delay: 0.2s;
  }

  @keyframes fadeInUp {
    from {
      opacity: 0;
      transform: translateY(20px);
    }

    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
}
</style>